from random import randint
from tornado import gen
from base.BaseHandler import AuthHandler, BaseHandler
from base.Models import Users
from base.SmtpEmailHandler import SendEmail
from config import config


class UserHandler(AuthHandler):
    @gen.coroutine
    def get(self):
        result = self.result()
        try:
            user = self.session.query(Users).filter_by(id=self.user_id, is_delete=0).first()
            if not user:
                self.data_except("当前用户不存在！")
            data = {
                "user_head_img": user.head_img,
                "user_name": user.nick_name,
                "email": user.email,
                "create_time": str(user.create_time)
            }
            result["status"] = 1
            result["msg"] = "数据获取成功！"
            result["data"] = data
        except Exception as e:
            self.logger.error(e)
            result = self.check_except_zh(e)
        self.write(result)

    @gen.coroutine
    def post(self):
        # 更新用户信息
        result = self.result()
        try:
            data = self.get_body()
            
            result["status"] = 1
            result["msg"] = "新增公司成功！"
        except Exception as e:
            self.session.rollback()
            print(e)
            result = self.check_except_zh(e)
        self.write(result)

    @gen.coroutine
    def put(self):
        # 密码更改
        result = self.result()
        try:
            data = self.get_body()
            old_password = self.data_not_null(data, "old_password", "请输入旧密码！")
            password_1 = self.data_not_null(data, "password_1", "请输入密码！")
            password_2 = self.data_not_null(data, "password_2", "请再次输入密码！")

            if password_1 != password_2:
                self.data_except("新密码输入不一致！")
            user_verify = self.session.query(Users).filter_by(id=self.user_id, password=old_password, is_delete=0).first()
            if not user_verify:
                self.data_except("旧密码输入错误！")
            user_verify.password = password_1
            self.record_user_operation(self.user_id, self.user_name, todo="用户更改密码")
            self.session.commit()
            result["status"] = 1
            result["msg"] = "密码更改成功，请重新登录！"
            self.logger.info(f"用户-{self.user_name}-更改密码")
        except Exception as e:
            self.logger.error(e)
            result = self.check_except_zh(e)
        self.write(result)


class RegisterHandler(BaseHandler):
    @gen.coroutine
    def post(self):
        # 用户注册
        result = self.result()
        try:
            data = self.get_body()
            nick_name = self.data_not_null(data, "nick_name", "请输入昵称！")
            email = self.data_not_null(data, "email", "请输入邮箱！")
            verification_code = self.data_not_null(data, "verification_code", "请输入验证码！")
            password_1 = self.data_not_null(data, "password_1", "请输入密码！")
            password_2 = self.data_not_null(data, "password_2", "请再次输入密码！")

            try:
                code_exit = self.redis_conn.get(email)
            except Exception as e:
                print(e)
                code_exit = config["ver_code"]
            if not code_exit:
                self.data_except("请获取验证码！")
            if int(verification_code) != int(code_exit):
                self.data_except("验证码无效！")
            if password_1 != password_2:
                self.data_except("密码输入不一致！")

            user_verify = self.session.query(Users)
            if user_verify.filter_by(email=email).count() > 0:
                self.data_except("该邮箱已注册！")
            if user_verify.filter_by(nick_name=nick_name).count() > 0:
                self.data_except("该用户名已存在！")

            user = Users(nick_name=nick_name, email=email, password=password_1)
            self.session.add(user)
            self.session.commit()
            self.record_user_operation(user.id, nick_name, todo=f"用户-{nick_name}-注册成功")
            self.session.commit()
            result["status"] = 1
            result["msg"] = "账户注册成功！"
            self.logger.info(f"用户-{nick_name}-注册成功")
        except Exception as e:
            self.session.rollback()
            self.logger.error(e)
            result = self.check_except_zh(e)
        self.write(result)


class ForgotPasswordHandler(BaseHandler):
    @gen.coroutine
    def post(self):
        # 忘记密码，更改密码
        result = self.result()
        try:
            data = self.get_body()
            email = self.data_not_null(data, "email", "请输入邮箱！")
            ver_code = self.data_not_null(data, "ver_code", "请输入验证码！")
            password_1 = self.data_not_null(data, "password_1", "请输入密码！")
            password_2 = self.data_not_null(data, "password_2", "请再次输入密码！")

            try:
                code_exit = self.redis_conn.get(email)
            except Exception as e:
                print(e)
                code_exit = config["ver_code"]
            if not code_exit:
                self.data_except("请获取验证码！")
            if int(ver_code) != int(code_exit):
                self.data_except("验证码无效！")
            if password_1 != password_2:
                self.data_except("密码输入不一致！")

            email_verify = self.session.query(Users).filter_by(email=email, is_delete=0).first()
            if not email_verify:
                self.data_except("该邮箱不存在！")
            email_verify.password = password_1
            self.record_user_operation(email_verify.id, email_verify.nick_name, todo="用户忘记密码，已更改密码！")
            self.session.commit()
            result["status"] = 1
            result["msg"] = "重置密码成功，2秒后去到登录页！"
            self.logger.info(f"用户-{email_verify.nick_name}-忘记密码，已重置密码。")
        except Exception as e:
            self.session.rollback()
            self.logger.error(e)
            result = self.check_except_zh(e)
        self.write(result)


class ChangeEmailHandler(AuthHandler):
    @gen.coroutine
    def post(self):
        # 更改邮箱
        result = self.result()
        try:
            data = self.get_body()
            email = self.data_not_null(data, "email", "请输入邮箱！")
            verification_code = self.data_not_null(data, "verification_code", "请输入验证码！")

            # redis连接失败，则使用万能码
            try:
                code_exit = self.redis_conn.get(email)
            except Exception as e:
                print(e)
                code_exit = config["ver_code"]
            print(code_exit)
            if not code_exit:
                self.data_except("请获取验证码！")
            if int(verification_code) != int(code_exit):
                self.data_except("验证码无效！")

            user = self.session.query(Users).filter_by(id=self.user_id, is_delete=0).first()
            email_verify = self.session.query(Users).filter_by(email=email, is_delete=0).first()
            if email_verify:
                self.data_except("该邮箱已注册！")
            user.email = email
            self.record_user_operation(user.id, user.nick_name, todo=f"用户更改邮箱账号，更改为 {email}")
            self.session.commit()
            result["status"] = 1
            result["msg"] = "邮箱账号更改成功！"
            self.logger.info(f"用户-{user.nick_name}-更改邮箱为 {email}")
        except Exception as e:
            self.session.rollback()
            self.logger.error(e)
            result = self.check_except_zh(e)
        self.write(result)


class UserUnsubscribeHandler(AuthHandler):
    @gen.coroutine
    def post(self):
        # 用户注销账号
        result = self.result()
        try:
            user_verify = self.session.query(Users).filter_by(id=self.user_id, is_delete=0).first()
            if not user_verify:
                self.data_except("账户不存在！")
            user_verify.is_delete = 1
            self.record_user_operation(user_verify.id, user_verify.nick_name, todo="用户确认账号注销！")
            self.session.commit()
            result["status"] = 1
            result["msg"] = "账号注销成功，感谢您的使用！"
            self.logger.info(f"用户-{user_verify.nick_name}-确认注销账号")
        except Exception as e:
            self.session.rollback()
            self.logger.error(e)
            result = self.check_except_zh(e)
        self.write(result)


class VerificationCodeHandler(BaseHandler):
    @gen.coroutine
    def get(self):
        # 获取验证码
        result = self.result()
        try:
            data = self.get_params()
            email = self.data_not_null(data, "email", "请输入邮箱！")

            v_code = randint(10001, 999999)
            try:
                if self.redis_conn.get(email):
                    v_code = self.redis_conn.get(email)
                else:
                    self.redis_conn.set(email, v_code, ex=60*3, nx=True)  # ex:过期时间（秒），nx为true：不存在则set操作才执行
            except Exception as e:
                print(e)
                v_code = config["ver_code"]     # redis连接失败，则使用万能码

            print(v_code)
            title = "验证码"
            content = "本次验证码为：%s，验证码有效期为3分钟。" % str(v_code)
            send_email = SendEmail(title=title, content=content, receiver=email)
            send_email.send_email()

            result["status"] = 1
            result["msg"] = "验证码发送成功，请前往邮箱查看！"
            self.logger.info(f"向邮箱 {email} 发送验证码！")
        except Exception as e:
            self.logger.error(e)
            result = self.check_except_zh(e)
        self.write(result)

